<?
$tpls = Mail_Tpl::find()->columns('mail_tpl_id,name,subject')->order('name')->getAll();
$planTplIds = $plan->tpls->toHashmap('mail_tpl_id', 'mail_tpl_id');


function renderPeriodType($val = null, $i = null)
{
    $captions = array(
        '天',
        '个工作日',
        '个休息日',
        '个星期一',
        '个星期二',
        '个星期三',
        '个星期四',
        '个星期五',
        '个星期六',
        '个星期日',
    );

    return Q::control('dropdownlist', 'period_type_' . $i, array('value' => $val, 'items' => Mail_Period::period_types(), 'captions' => $captions, 'name' => 'period_type[]'));
}

?>

<?php $this->_extends('_layouts/default_layout'); ?>

<?php $this->_block('title'); ?><?= $title ?><?php $this->_endblock(); ?>
<?php $this->_block('js'); ?>
<script src="<?=$_BASE_DIR?>js/jquerytools/1.2.5/jquery.tools.min.js"></script>
<script src="<?=$_BASE_DIR?>js/jqueryui/1.8.12/jquery-ui.min.js"></script>

<script type="text/javascript">


    $(function() {

        $tplTable = $('#tplTable');
        $tplSelectPanel = $('#tplSelectPanel');
        $selectTplResult = $('#selectTplResult');

        $('img.unbind', $tplTable).live('click', function() {
            var $row = $(this).closest('tr');
            var mail_plan_tpl_id = $('input[name="mail_plan_tpl_id[]"]', $row).val();
            var $img = $(this);

            $.ajax({
                url:"<?=url('/planUnbindTpl')?>",
                data: 'mail_plan_tpl_id=' + mail_plan_tpl_id,
                dataType:'json',
                type:'post',
                beforeSend: function() {
                    $img.attr('src', '<?=$_BASE_DIR?>img/icon/loading.gif');
                },
                success:function(res) {
                    if (res.ack == 'success') {
                        $row.remove();
                        resortPlanTplNums();
                    } else {
                        alert(res.msg);
                    }
                },
                complete:function() {
                    $img.attr('src', '<?=$_BASE_DIR?>img/icon/Delete.png');
                }
            });
        });


        $('tbody', $tplTable).sortable({
            delay: 500,
            placeholder: 'highlight',
            revert: true,
            update:resortPlanTpls,
            forcePlaceholderSize: true,
            handle: 'td.handle'
        });

        $('#selectTpl').click(function() {
            $selectTplResult.hide();
        });
        $('#btnSelectTpl').click(function() {
            var tplIds = [];

            $(':checked', $tplSelectPanel).each(function() {
                tplIds.push($(this).val());
            });

            $.ajax({
                url:"<?=url('/planBindTpl')?>",
                data: 'tplIds=' + tplIds.join(',') + '&mail_plan_id=' +<?=$_GET['pid']?>,
                dataType:'json',
                type:'post',
                success:function(res) {
                    if (res.ack == 'success') {
                        appendTpls(res.planTpls);
                        $selectTplResult
                                .hide()
                                .html('<font color="green" size="5">添加成功</font>')
                                .show('slow')

                    } else {
                        alert(res.msg);
                    }
                }
            });
        });


        $("#selectTpl, #selectAddress").overlay({
            mask: {
                color: '#999',
                loadSpeed: 200,
                opacity: 0.9
            },
            onLoad:function() {
                var panelMaxHeight = $(window).height()  - $tplSelectPanel.scrollTop()  - 80;
                var contentHeight = $tplSelectPanel.find('table').height() + 110;
                if(contentHeight > panelMaxHeight) contentHeight = panelMaxHeight;
                $tplSelectPanel.css('height',contentHeight);
            }
        });

        function resortPlanTpls() {

            var ids = [], id;

            $('tbody tr', $tplTable).each(function() {
                id = $('input[name="mail_plan_tpl_id[]"]', this).val();
                ids.push(id);
            });

            $.ajax({
                type:'post',
                dataType :'json',
                url:"<?=url('/resortPlanTpl')?>",
                data:'planTplIds=' + ids.join(','),
                success:function(data) {
                    if (data.ack != 'success') {
                        alert(data.errorMsg);
                    } else {
                        resortPlanTplNums();
                    }
                }
            });

        }

        function resortPlanTplNums() {
            var num = 1;

            $('tbody tr', $tplTable).each(function() {
                $('span.num', $(this)).html(num);
                num++;
            });
        }
    });


    function appendTpls(planTpls) {
        var html = '';
        var num = $('tbody tr', $tplTable).length;

        $.each(planTpls, function(index, planTpl) {
            html += '<tr>' +
                    '<td class="handle"></td>' +
                    '<td><span class="num">' +
                    (++num) +
                    '</span><input type="hidden" name="mail_plan_tpl_id[]" value="' + planTpl.mail_plan_tpl_id + '">' +
                    '<input type="hidden" name="mail_tpl_id[]" value="' + planTpl.mail_tpl_id + '">' +
                    '</td>' +

                    '<td><a href="<?=url('mail/tpledit')?>/tid/' + planTpl.mail_tpl_id + '" target="_blank">' + planTpl.name + '</a></td>' +
                    '<td>' + planTpl.subject + '</td>' +
                    '<td><input name="send_time[]" value="10:00:00"></td>' +

                    '<td>' +
                    '上封信之后的第' +
                    '<input name="interval_periods[]" value="1" size="1">' +
                    '<select name="period_type[]" >' +
                    '<option value="1" >天</option>' +
                    '<option value="2" >个工作日</option>' +
                    '<option value="3" >个休息日</option>' +
                    '<option value="4" >个星期一</option>' +
                    '<option value="5" >个星期二</option>' +
                    '<option value="6" >个星期三</option>' +
                    '<option value="7" >个星期四</option>' +
                    '<option value="8" >个星期五</option>' +
                    '<option value="9" >个星期六</option>' +
                    '<option value="10" >个星期日</option>' +
                    '</select>' +
                    '</td>' +

                    '<td>' + planTpl.type + '</td>' +
                    '<td>' + planTpl.profession + '</td>' +
                    '<td><img src="<?=$_BASE_DIR?>img/icon/Delete.png" title="解除绑定" class="unbind"/></td>' +
                    '</tr>';
        });

        $('tbody', $tplTable).append(html);
    }
</script>
<style type="text/css">
    fieldset {
        padding: 20px
    }

    td.handle {
        cursor: move;
        background: url(<?=$_BASE_DIR?>img/handle.png) no-repeat 0 7px;
        width: 4px;
    }

    #tplTable img {
        cursor: pointer
    }

    legend {
        color: #000000;
    }

    fieldset, legend {
        -moz-border-radius: 6px;
        -webkit-border-radius: 6px;
        -moz-box-shadow: 0 0 50px #ccc;
        -webkit-box-shadow: 0 0 20px #ccc;
    }

    .overlay {
        background-color: #fff;
        display: none;
        width: 350px;
        padding: 15px;
        text-align: left;
        border: 2px solid #333;
        overflow-y: auto;

        opacity: 0.8;
        -moz-border-radius: 6px;
        -webkit-border-radius: 6px;
        -moz-box-shadow: 0 0 50px #ccc;
        -webkit-box-shadow: 0 0 50px #ccc;
    }

    .overlay td {
        background: #ffffff
    }

    .overlay h2 {
        padding: 10px;
        border-bottom: 1px solid #333;
        font-size: 20px;
    }


</style>
<?php $this->_endblock('js'); ?>

<?php $this->_block('actionBar'); ?>
<?php $this->_endblock('actionBar'); ?>

<?php $this->_block('contents'); ?>

<? if (isset($errorMsg)): ?>
<div class="error"><?=$errorMsg?></div>
<? endif ?>


<form id=mainForm method="post" style="margin-bottom: 60px">
    <fieldset>
        <legend>
            <strong>计划名称</strong> <input name="name" value="<?=$plan->name?>">
        </legend>

        <? if (isset($_GET['pid'])) { ?>
        <strong>此计划包含下列邮件模板</strong>
        <input id="selectTpl" type="button" value="添加邮件模板" rel="#tplSelectPanel">
        <table class=dataTable style="margin-top: 10px" id="tplTable">
            <thead>
            <tr>
                <th></th>
                <th>序号</th>
                <th>模板名称</th>
                <th>主题</th>
                <th>发信时间(当地时间)</th>
                <th>发信日期</th>
                <th>模板分类</th>
                <th>行业分类</th>
                <th></th>
            </tr>
            </thead>
            <tbody>
                <? foreach ($plan->tpls as $i => $pt): ?>
            <tr>
                <td class="handle"></td>
                <td>
                    <span class="num"><?=$i + 1?></span>
                    <input type="hidden" name="mail_plan_tpl_id[]" value="<?=$pt->id()?>">
                    <input type="hidden" name="mail_tpl_id[]" value="<?=$pt->mail_tpl_id?>">
                </td>
                <td><a href="<?=url('mail/tpledit', 'tid/' . $pt->mail_tpl_id)?>" target="_blank"><?=$pt->name()?></a>
                </td>
                <td><?=$pt->subject()?></td>
                <td><input name="send_time[]" value="<?=$pt->send_time()?>"></td>
                <td>
                    上封信之后的第<input name="interval_periods[]" value="<?=$pt->interval_periods()?>"
                                  size="1"><?=renderPeriodType($pt->period_type, $i)?>
                </td>
                <td><?=$pt->type()?></td>
                <td><?=$pt->profession()?></td>
                <td><img src="<?=$_BASE_DIR?>img/icon/Delete.png" title="解除绑定" class="unbind"/></td>
            </tr>
                <? endforeach ?>
            </tbody>

        </table>
        <br>
        <strong>循环执行</strong> 当邮件计划执行到最后一个模板后，重新从第<input size="1" name="loop_tpl_num"
                                                         value="<?=$plan->loop_tpl_index + 1?>">个模板开始。（0为不循环）

        <!--        <br><br><br><br><br>


        <strong>此计划应用于下列邮箱地址</strong>
        <input id="selectAddress" type="button" value="添加邮箱地址" rel="#addressSelectPanel">

        <table class=dataTable id="addressTable">
            <thead>
            <tr>
                <th>邮箱地址</th>
                <th>称呼</th>
                <th>状态</th>
                <th>循环次数</th>
                <th>上封信发出时间</th>
                <th>下封信序号</th>
            </tr>
            </thead>
            <tbody>
            <?/* foreach ($plan->addresses as $i => $pa): */?>
            <tr>
                <td>
                    <?/*=$pa->address()*/?>
                    <input type="hidden" name="mail_address_plan_id[]" value="<?/*=$pa->id()*/?>">
                    <input type="hidden" name="mail_address_id[]" value="<?/*=$pa->mail_address_id*/?>">
                </td>
                <td><?/*=$pa->customer_name()*/?></td>
                <td><?/*=//renderStatus($pa->status, $i)*/?></td>
                <td><?/*=$pa->loop_cnt*/?></td>
                <td><?/*=$pa->last_tpl_send_datetime*/?></td>
                <td><?/*=$pa->next_tpl_num */?></td>
            </tr>
                <?/* endforeach */?>
            </tbody>
        </table>-->
        <br>
        <? } // EO if($_GET['pid']) ?>
        <input type="submit" value="保存更改">
</form>

</fieldset>


<div id="tplSelectPanel" class="overlay">
    <h2>添加邮件模板</h2>

    <table class=dataTable>
        <thead>
        <tr>
            <th></th>
            <th>模板名称</th>
            <th>主题</th>
        </tr>
        </thead>
        <tbody>
        <? foreach ($tpls as $t): ?>
        <tr>
            <td><input type="checkbox" value="<?=$t->id()?>"></td>
            <td><?=$t->name?></td>
            <td><?=$t->subject?></td>
        </tr>
            <? endforeach; ?>
        </tbody>
    </table>

    <input type="button" value="添加选中的模板" id="btnSelectTpl">
    <input type="button" value="返回" class="close">

    <div id="selectTplResult"></div>

</div>
<?php $this->_endblock(); ?>